<template>
  <div v-show="getShow" :title="dialogTitle">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-row>
        <el-col :span="24" style="padding-right: 15%; padding-left: 10px">
          <el-form-item>
            <LoginFormTitle style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="23">
          <el-form-item label="用户昵称" prop="nickname">
            <el-input v-model="formData.nickname" placeholder="请输入用户昵称" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="23">
          <el-form-item label="手机号码" prop="mobile">
            <el-input v-model="formData.mobile" maxlength="11" placeholder="请输入手机号码" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="23">
          <el-form-item label="邮&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;箱" prop="email">
            <el-input v-model="formData.email" maxlength="50" placeholder="请输入邮箱" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="23">
          <el-form-item v-if="formData.id === undefined" label="用户名称" prop="username">
            <el-input v-model="formData.username" placeholder="请输入用户名称" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="23">
          <el-form-item label="用户性别">
            <el-select v-model="formData.sex" placeholder="请选择">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="23">
          <el-form-item v-if="formData.id === undefined" label="用户密码" prop="password">
            <el-input
              v-model="formData.password"
              placeholder="请输入用户密码"
              show-password
              type="password"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="23">
          <el-form-item v-if="formData.id === undefined" label="确认密码" prop="confirmPassword">
            <el-input
              v-model="formData.confirmPassword"
              placeholder="确认密码"
              show-password
              type="password"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12" class="mt-15px">
          <el-form-item label="验&nbsp;&nbsp;证&nbsp;&nbsp;码" prop="password">
            <el-input v-model="formData['code']" :placeholder="t('login.codePlaceholder')" />
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <div></div>
        </el-col>
        <el-col :span="10">
          <el-image :src="codeUrl" @click="getCode" draggable="false">
            <template #placeholder>
              <el-icon>
                <Picture />
              </el-icon>
            </template>
            <template #error> #error </template>
          </el-image>
        </el-col>
      </el-row>
    </el-form>
    <!-- 按钮部分 -->
    <el-row>
      <div class="mt-15px w-[100%]">
        <XButton
          :loading="loading"
          :title="t('login.register')"
          class="w-[100%]"
          type="primary"
          :disabled="formLoading"
          @click="submitForm"
        />
      </div>
      <div class="mt-15px w-[100%]">
        <XButton
          :loading="loading"
          :title="t('login.clear')"
          class="w-[100%]"
          type="default"
          @click="resetForm()"
        />
      </div>
      <!-- <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="resetForm()">清 空</el-button> -->
    </el-row>
    <div class="mt-15px w-[100%]">
      <XButton :title="t('login.hasUser')" class="w-[100%]" @click="handleBackLogin()" />
    </div>
  </div>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
// import { defaultProps, handleTree } from '@/utils/tree'
import * as PostApi from '@/api/system/post'
// import * as DeptApi from '@/api/system/dept'
import * as UserApi from '@/api/system/user'
import { FormRules } from 'element-plus'
import { LoginStateEnum, useLoginState } from './useLogin'
import * as LoginApi from '@/api/login'
import { userregist165 } from '@/api/regist'
import * as authUtil from '@/utils/auth'

const { handleBackLogin, getLoginState } = useLoginState()
defineOptions({ name: 'RegistForm' })
import LoginFormTitle from './LoginFormTitle.vue'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const getShow = computed(() => unref(getLoginState) === LoginStateEnum.REGISTER)
// const dialogVisible = ref(true) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用

const formData = ref({
  uuid: '',
  code: '',
  codev: '',
  nickname: '',
  deptId: '',
  mobile: '',
  email: '',
  id: undefined,
  username: '',
  password: '',
  confirmPassword: '',
  sex: undefined,
  postIds: [],
  remark: '',
  // status: CommonStatusEnum.ENABLE,
  roleIds: []
})
const formRules = reactive<FormRules>({
  username: [{ required: true, message: '用户名称不能为空', trigger: 'blur' }],
  nickname: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '用户密码不能为空', trigger: 'blur' }],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value: string, callback) => {
        if (value == '') {
          callback(new Error('请再次输入密码'))
        } else if (value != formData.value.password) {
          callback(new Error('两次输入的密码不一致!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],

  email: [
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: ['blur', 'change']
    }
  ],
  mobile: [
    {
      pattern: /^(?:(?:\+|00)86)?1(?:3[\d]|4[5-79]|5[0-35-9]|6[5-7]|7[0-8]|8[\d]|9[189])\d{8}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ]
})
const formRef = ref() // 表单 Ref
const deptList = ref<Tree[]>([]) // 树形结构
const postList = ref([] as PostApi.PostVO[]) // 岗位列表

const codeUrl = ref('')

// 验证密码和确认密码是否一致
// function confirmPassword() {
//   if (formData.value.password !== formData.value.confirmPassword) {
//     console.log('密码不正确')
//   }
// }
const getCode = async () => {
  // 先清空验证码的输入
  // schema['code'] = "";
  // 获取验证码
  codeUrl.value = "";
  const res = await LoginApi.captchaImage();
  // captcha['codev'] = res.codev
  // captcha['code'] = res.codev
  formData.value.uuid =  res.uuid
  formData.value.code = res.codev
  formData.value.codev = res.codev
  codeUrl.value = "data:image/gif;base64," + res.img
};
getCode();


/** 提交表单 */
const emit = defineEmits(['close', 'success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    if (formData.value.code != formData.value.codev) {
      message.error('验证码错误！重新输入')
    } else {
      authUtil.setTenantId('165')
      const res = await userregist165(formData.value)
      console.info("注册的id", res)

      message.success(t('common.registerSuccess')) // 注册成功提示信息
      emit('close') // 关闭模态框
      resetForm() // 注册信息置空
    }

    // await UserApi.createUser(data)
    // message.success(t('common.createSuccess'))
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    uuid: '',
    code: '',
    codev: '',
    nickname: '',
    deptId: '',
    mobile: '',
    email: '',
    id: undefined,
    username: '',
    password: '',
    confirmPassword: '',
    sex: undefined,
    postIds: [],
    remark: '',
    // status: CommonStatusEnum.ENABLE,
    roleIds: []
  }
  formRef.value?.resetFields()
}
</script>
